package com.szmmsoft.mp.common.exception;

import com.szmmsoft.mp.common.model.R;
import com.szmmsoft.mp.common.until.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Description of the class.
 *
 * @author ethan
 * @version 1.0.0
 * @since 2024-10-15
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 业务异常
     *
     * @param businessException
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public R<Void> processBusinessException(BusinessException businessException) {
        log.error("业务错误:{}", businessException.getMsg());
        return R.error(businessException.getCode(), businessException.getMsg(),LoginUtil.getRequestId());
    }

    /**
     * 其他异常
     *
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public R<Void> processException(Exception exception) {
        log.error("其他异常:{}", exception.toString());
        return R.error(exception.toString(), LoginUtil.getRequestId());
    }
    /**
     * SpringMVC参数绑定，Validator校验不正确
     */
    @ExceptionHandler(BindException.class)
    public R<String> bindException(BindException ex) {
        log.error("校验错误:{}", ex.toString());
        FieldError fieldError = ex.getFieldError();
        assert fieldError != null;
        return R.error(BusinessCode.VALIDATION_ERROR.getCode(),fieldError.getDefaultMessage(),LoginUtil.getRequestId());
    }
    /**
     * SpringMVC参数绑定，Validator校验不正确
     */
    @ExceptionHandler(ValidatorException.class)
    public R<String> validatorException(ValidatorException ex) {
        log.error("逻辑校验错误:{}", ex.toString());
        return R.error(BusinessCode.VALIDATION_ERROR.getCode(),ex.getMsg(),LoginUtil.getRequestId());
    }
}
